package com.erp.erp_ui.information.service;

import com.erp.enums.DictionaryLxEnum;
import com.erp.enums.DictionaryTypeEnum;
import com.erp.enums.ModuleTypeEnum;
import com.erp.erp_entitys.warehouse.entity.AnnexEntity;
import com.erp.erp_entitys.warehouse.req.CustomerInfoReq;
import com.erp.erp_entitys.warehouse.req.CustomerQueryReq;
import com.erp.erp_entitys.warehouse.req.DictionaryInfoReq;
import com.erp.erp_entitys.warehouse.rsp.*;
import com.erp.erp_servers.Department.IDepartmentService;
import com.erp.erp_servers.warehouse.IAnnexService;
import com.erp.erp_servers.warehouse.IOtherOutStockService;
import com.erp.erp_servers.warehouse.IStockService;
import com.erp.erp_ui.information.req.AnnexAddReq;
import com.erp.erp_ui.information.req.BasicInfoReq;
import com.erp.erp_ui.information.vo.BasicInfoVo;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.erp_ui.warehouse.req.AnnexReq;
import com.erp.erp_ui.warehouse.vo.DictionaryInfoVo;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName : BasicInformationService
 * @Description : 基础信息业务逻辑层
 * @Author : lst
 * @Date: 2021-03-19 17:54
 */
@Service
public class BasicInformationService {
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BasicInformationService.class);

    /**
     * 库存接口
     */
    private final IStockService stockService;

    /**
     * 其它出库接口
     */
    private final IOtherOutStockService otherOutStockService;

    /**
     * 部门接口
     */
    private final IDepartmentService departmentService;

    /**
     * 附件接口
     */
    private final IAnnexService annexService;

    @Autowired
    public BasicInformationService(IStockService stockService,
                                   IOtherOutStockService otherOutStockService,
                                   IDepartmentService departmentService,
                                   IAnnexService annexService) {
        this.stockService = stockService;
        this.otherOutStockService = otherOutStockService;
        this.departmentService = departmentService;
        this.annexService = annexService;
    }

    /**
     * 获取基础信息
     * @param req 指定获取哪些字典信息
     * @param operator 操作员
     * @param operationNo 操作员编码
     * @return 基础信息
     */
    public BasicInfoVo getBasicInfo(BasicInfoReq req, String operator, String operationNo){
        BasicInfoVo vo = new BasicInfoVo();
        if(StringUtils.isNotBlank(req.getCustomerInfo())){
            //客户信息
            List<CustomerInfoRsp> list = otherOutStockService.getCustomerAllInfo(10, null, null);
            //获取客户信息
            getCustomerInfos(vo, list);
        }
        if(StringUtils.isNotBlank(req.getCompanyInfo())){
            //公司信息
            List<CompanyInfoRsp> list = stockService.getCompanyInfo();
            vo.setCompanyInfo(list);
        }
        if(StringUtils.isNotBlank(req.getTransitPlace())){
            //起运地
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.OTHER.getId(), DictionaryLxEnum.TRANSIT_PLACE.getId());
            vo.setTransitPlace(list);
        }
        if(StringUtils.isNotBlank(req.getCountry())){
            //国家
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.OTHER.getId(), DictionaryLxEnum.COUNTRY.getId());
            vo.setCountry(list);
        }
        if(StringUtils.isNotBlank(req.getCurrencyInfo())){
            //币种
            getCurrencyInfo(vo);
        }
        if(StringUtils.isNotBlank(req.getPriceTerms())){
            //价格术语
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.SETTLEMENT.getId(), DictionaryLxEnum.PRICE_TERMS.getId());
            vo.setPriceTerms(list);
        }
        if(StringUtils.isNotBlank(req.getBusinessModel())){
            //业务模式
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.OTHER.getId(), DictionaryLxEnum.BUSINESS_MODEL.getId());
            vo.setBusinessModel(list);
        }
        if(StringUtils.isNotBlank(req.getPaymentType())){
            //付款类型
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.SETTLEMENT.getId(), DictionaryLxEnum.PAYMENT_TYPE.getId());
            vo.setPaymentType(list);
        }
        if(StringUtils.isNotBlank(req.getUnitOfQuantity())){
            //数量单位
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.COMMODITY_INFO.getId(), DictionaryLxEnum.UNIT_OF_QUANTITY.getId());
            vo.setUnitOfQuantity(list);
        }
        if(StringUtils.isNotBlank(req.getModeOfTransport())){
            //运输方式
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.BASIC_INFORMATION.getId(), DictionaryLxEnum.MODE_OF_TRANSPORT.getId());
            vo.setModeOfTransport(list);
        }
        if(StringUtils.isNotBlank(req.getContainerModel())){
            //货柜型号
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.BASIC_INFORMATION.getId(), DictionaryLxEnum.CONTAINER_MODEL.getId());
            vo.setContainerModel(list);
        }
        if(StringUtils.isNotBlank(req.getCostType())){
            //费用类型
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.SETTLEMENT.getId(), DictionaryLxEnum.COST_TYPE.getId());
            vo.setCostType(list);
        }
        if(StringUtils.isNotBlank(req.getWarehouseInfo())){
            //仓库信息
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.WAREHOUSE_MAINTENANCE.getId(), DictionaryLxEnum.MAIN_WAREHOUSE_MAINTENANCE.getId());
            vo.setWarehouseInfo(list);
        }
        if(StringUtils.isNotBlank(req.getInspectionProgress())){
            //验货进度
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.OTHER.getId(), DictionaryLxEnum.INSPECTION_PROGRESS.getId());
            vo.setInspectionProgress(list);
        }
        if(StringUtils.isNotBlank(req.getReceivePayment())){
            //收款类型
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.SETTLEMENT.getId(), DictionaryLxEnum.RECEIVE_PAYMENT_TYPE.getId());
            if (list.size() == 12) {
                //位置调换(暂用)
                List<DictionaryInfoRsp> newList = new LinkedList<>();
                for(DictionaryInfoRsp info : list){
                    if(info.getCode().equals("SK-011") || info.getCode().equals("SK-012")){
                        continue;
                    }
                    newList.add(info);
                    if(info.getCode().equals("SK-006")){
                        newList.add(list.get(10));
                        newList.add(list.get(11));
                    }
                }
                vo.setReceivePayment(newList);
            } else {
                vo.setReceivePayment(list);
            }

        }
        if(StringUtils.isNotBlank(req.getCustomsCode())){
            //海关编码
            List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.COMMODITY_INFO.getId(), DictionaryLxEnum.CUSTOMS.getId());
            vo.setCustomsCode(list);
        }
        return vo;
    }

    /**
     * 获取币种信息
     * @param vo 返回字典信息
     */
    private void getCurrencyInfo(BasicInfoVo vo){
        List<DictionaryInfoRsp> list = getDictionaryInfo(DictionaryTypeEnum.SETTLEMENT.getId(), DictionaryLxEnum.CURRENCY.getId());
        List<DictionaryInfoVo> dictionaryVos = new ArrayList<>();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        for(DictionaryInfoRsp infoRsp : list){
            DictionaryInfoVo infoVo = new DictionaryInfoVo();
            BeanUtils.copyProperties(infoRsp, infoVo);
            //汇率转换
            //获取汇率
            String exchangeRate = infoRsp.getExchangeRate();
            if(StringUtils.isBlank(exchangeRate)){
                infoVo.setExchangeRate(new BigDecimal("0"));
            }else{
                infoVo.setExchangeRate(new BigDecimal(exchangeRate));
            }

            dictionaryVos.add(infoVo);
        }
        vo.setCurrencyInfo(dictionaryVos);
    }

    /**
     * 获取字典信息
     * @param typeId 大类
     * @param lxId 小类
     * @return 字典信息
     */
    private List<DictionaryInfoRsp> getDictionaryInfo(int typeId, int lxId){
        //初始化字段对象
        DictionaryInfoReq dictionaryInfosReq = new DictionaryInfoReq();
        dictionaryInfosReq.setType(typeId);
        dictionaryInfosReq.setLx(lxId);
        return stockService.getDictionaryInfo(dictionaryInfosReq);
    }

    /**
     * 获取客户信息
     * @param vo 回参对象
     * @param list 客户信息
     */
    private void getCustomerInfos(BasicInfoVo vo, List<CustomerInfoRsp> list){
        if(!CollectionUtils.isEmpty(list)){
            //客户信息
            List<DictionaryInfoRsp> customerInfo = new ArrayList<>();
            for(CustomerInfoRsp info : list){
                //1.客户信息
                DictionaryInfoRsp rsp = new DictionaryInfoRsp();
                rsp.setName(info.getName());
                rsp.setCode(info.getCode());
                rsp.setSalesman(info.getSalesman());
                rsp.setSalesmanCode(info.getSalesmanCode());
                rsp.setAccountPeriod(info.getAccountPeriod());

                customerInfo.add(rsp);

            }
            vo.setCustomerInfo(customerInfo);
        }
    }


    /**
     * 获取客户信息
     * @param info 查询参数
     * @return 客户信息
     */
    public BasicInfoVo getCustomerInfo(String info, String code){
        List<CustomerInfoRsp> list = new ArrayList<>();
        //获取当前登陆用户所管理的用户code
        if (StringUtils.isEmpty(code)) {
            list = otherOutStockService.getCustomerAllInfo(20, info, null);
        } else {
            String userCode = departmentService.getUserCodeByTheCurrentUser(code);
            list = otherOutStockService.getCustomerAllInfo(20, info, userCode);
        }

        //初始化回参
        BasicInfoVo vo = new BasicInfoVo();
        if(!CollectionUtils.isEmpty(list)){
            //客户信息
            List<DictionaryInfoRsp> customerInfo = new ArrayList<>();
            for(CustomerInfoRsp infoRsp : list){
                if(!StringUtils.isEmpty(code)){
                    boolean flag = infoRsp.getType().equals("0") || infoRsp.getType().equals("1");
                    if(!flag){
                        //只获取合作客户(type = 0 或 type = 1)
                        continue;
                    }
                }
                //1.客户信息
                DictionaryInfoRsp rsp = new DictionaryInfoRsp();
                rsp.setName(infoRsp.getName());
                rsp.setCode(infoRsp.getCode());
                rsp.setCustomerLevelName(infoRsp.getCustomerLevelName());
                rsp.setCustomerLevelCode(infoRsp.getCustomerLevelCode());
                rsp.setCity(infoRsp.getCity());
                //客户账期
                rsp.setAccountPeriod(infoRsp.getAccountPeriod());
                //信用额度
                BigDecimal creditQuota = new BigDecimal("0");
                if(StringUtils.isNotEmpty(infoRsp.getCreditQuota())){
                    creditQuota = new BigDecimal(infoRsp.getCreditQuota());
                }
                rsp.setCreditQuota(creditQuota);

                //客户简称
                if(StringUtils.isNotEmpty(infoRsp.getAbbreviation())){
                    rsp.setAbbreviation(infoRsp.getAbbreviation());
                }

                //国家编码
                rsp.setCountryCode(infoRsp.getCountryCode());

                //客户来源
                String sourceOfCustomerCode = infoRsp.getSourceOfCustomerCode();
                if(StringUtils.isNotEmpty(sourceOfCustomerCode)){
                    //客户来源
                    List<DictionaryInfoRsp> sourceOfCustomerList = getDictionaryInfo(DictionaryTypeEnum.CUSTOMER_INFO.getId(), DictionaryLxEnum.CUSTOMER_OF_SOURCE.getId());
                    if(!CollectionUtils.isEmpty(sourceOfCustomerList)){
                        rsp.setSourceOfCustomerName("");
                    }
                    for(DictionaryInfoRsp sourceInfo : sourceOfCustomerList){
                        if(sourceInfo.getCode().equals(sourceOfCustomerCode)){
                            rsp.setSourceOfCustomerName(sourceInfo.getName());
                            break;
                        }
                    }
                }

                customerInfo.add(rsp);
            }
            vo.setCustomerInfo(customerInfo);
        }

        return vo;
    }

    /**
     * 附件新增、修改
     * @param req 附件新增、修改入参
     * @param name 操作员名称
     * @param code 操作员编码
     */
    public R annexAdd(AnnexAddReq req, String name, String code) throws ParseException {
        if(CollectionUtils.isEmpty(req.getAnnexList())){
            //不存在附件
            if(!CollectionUtils.isEmpty(req.getDeleteAnnexIds())){
                //删除了所有附件,将该id关联的所有附件设为无效
                AnnexEntity annexReq = new AnnexEntity();
                annexReq.setParentId(req.getId());
                annexReq.setModuleId(req.getType());
                List<AnnexEntity> annexList = annexService.queryAll(annexReq);
                if(!CollectionUtils.isEmpty(annexList)){
                    for(AnnexEntity annex : annexList){
                        AnnexEntity updateAnnex= new AnnexEntity();
                        updateAnnex.setId(annex.getId());
                        //将被删除的附件设为失效
                        updateAnnex.setValid(DataIsValidEnum.INVALID.getId());
                        updateAnnex.setOperatorNo(code);
                        updateAnnex.setOperator(name);
                        updateAnnex.setUpdateTime(new Date());
                        annexService.update(updateAnnex);
                    }
                }
            }
        }else {
            //存在附件
            List<AnnexEntity> list = new ArrayList<>();
            for(AnnexReq annexReq : req.getAnnexList()){
                if(null != annexReq.getNews()){
                    //属于旧附件,不新增
                    continue;
                }
                AnnexEntity annex = new AnnexEntity();
                BeanUtils.copyProperties(annexReq, annex);
                //设置关联模块id
                annex.setModuleId(req.getType());
                //设置关联模块父id
                annex.setParentId(req.getId());
                //设置上传时间
                annex.setUploadTime(DateUtils.convertStringToDate(annexReq.getUploadTime(), DateUtils.DATE_TIME_PATTERN));
                //设置修改时间
                annex.setUpdateTime(new Date());
                //设置操作人
                annex.setOperator(name);
                //设置操作人编码
                annex.setOperatorNo(code);
                //设置数据有效
                annex.setValid(1);

                list.add(annex);
            }
            if(!CollectionUtils.isEmpty(list)){
                //附件批量新增
                annexService.batchInsert(list);
            }
            if(!CollectionUtils.isEmpty(req.getDeleteAnnexIds())){
                //删除了部分附件,将删除的附件设为无效
                for(Integer annexId : req.getDeleteAnnexIds()){
                    AnnexEntity updateAnnex= new AnnexEntity();
                    updateAnnex.setId(annexId);
                    //将被删除的附件设为失效
                    updateAnnex.setValid(DataIsValidEnum.INVALID.getId());
                    updateAnnex.setOperatorNo(code);
                    updateAnnex.setOperator(name);
                    updateAnnex.setUpdateTime(new Date());
                    annexService.update(updateAnnex);
                }
            }

        }

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 通过条件获取客户信息
     * @param req 查询条件实体
     * @return 客户信息
     */
    public PageInfo<CustomerInfoDataRsp> getCustomerByPage(CustomerQueryReq req){
        if(StringUtils.isEmpty(req.getName())
                && StringUtils.isEmpty(req.getType())
                && StringUtils.isEmpty(req.getSalesman())
                && StringUtils.isEmpty(req.getCode())
                && StringUtils.isEmpty(req.getAbbreviation())){
            //入参全部为空时,返回空
            List<CustomerInfoDataRsp> customerByQuery = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(customerByQuery);
            pageInfo.setList(customerByQuery);
            return pageInfo;
        }
        List<CustomerInfoDataRsp> customerByQuery = otherOutStockService.getCustomerByQuery(req);
        PageInfo pageInfo = new PageInfo(customerByQuery);
        pageInfo.setList(customerByQuery);
        return pageInfo;
    }

    /**
     * 根据客户编码获取客户联系人信息
     * @param req 客户编码
     * @return 客户联系人信息
     */
    public PageInfo<CustomerContactInfoDataRsp> getCustomerContactByPage(CustomerInfoReq req){
        List<CustomerContactInfoDataRsp> customerContactInfo = otherOutStockService.getCustomerContactInfoByCode(req);
        PageInfo pageInfo = new PageInfo(customerContactInfo);
        pageInfo.setList(customerContactInfo);
        return pageInfo;
    }
}
